<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('数据源ID')" prop="dataSourceId">-->
        <!--            <el-input v-model="form.dataSourceId" :placeholder="$t('数据源ID')" show-word-limit maxlength="32" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="12">
          <el-form-item :label="$t('数据集名称')" prop="dataSetName">
            <el-input v-model="form.dataSetName" :placeholder="$t('数据集名称')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('写入Sheet')" prop="sheetName">
            <el-input v-model="form.sheetName" :placeholder="$t('写入Sheet')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('展开方式')" prop="expansionMethod">
            <dictSelect
              v-model="form.expansionMethod"
              :clearable="true"
              dictionary="model_data_set_expansion_method"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('数据集类型')" prop="dataSetType">
            <dictSelect
              v-model="form.dataSetType"
              :clearable="true"
              dictionary="model_data_set_type"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.dataSetType === 'input'" :span="12">
          <el-form-item :label="$t('参数类型')" prop="paramType">
            <span slot="label">
              {{ $t('参数类型') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('单个字段：可通过字段列表直接设置') }}<br>
                  {{ $t('列表集合：需要录入表单“参数字段”，根据参数字段做为key获取列表值，并以字段列表中配置参数在进行设置值') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <dictSelect
              v-model="form.paramType"
              :clearable="true"
              dictionary="model_data_param_type"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.dataSetType === 'input' && form.paramType === 'LBJH'" :span="12">
          <el-form-item :label="$t('参数字段')" prop="paramField">
            <el-input v-model="form.paramField" :placeholder="$t('参数字段')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('查询SQL')" prop="searchSql">
            <textarea ref="searchSql" v-model="form.searchSql" class="codeSql" style="height:200px;width:600px;" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('字段列表') }}</span>
        <span v-if="form.dataSetType === 'sql'" style="float: right;font-size: 14px;">
          <template>
            <el-button v-hasPermi="['system:model:edit']" type="primary" size="mini" @click="getColumnBySql">{{ $t('刷新') }}</el-button>
          </template>
        </span>
      </div>

      <el-table :data="form.dataSetFieldList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段名称')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dataSetFieldList.' + scope.$index + '.fieldName'" :rules="dataSetFieldListRules.fieldName">
              <span v-if="form.dataSetType === 'input'"><el-input v-model="scope.row.fieldName" /></span>
              <span v-else>{{ scope.row.fieldName }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段类型')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dataSetFieldList.' + scope.$index + '.fieldType'" :rules="dataSetFieldListRules.fieldType">
              <dictSelect
                v-model="scope.row.fieldType"
                :clearable="true"
                dictionary="model_data_filed_type"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('起始单元格')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('起始单元格') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dataSetFieldList.' + scope.$index + '.startCell'" :rules="dataSetFieldListRules.startCell">
              <el-input v-model="scope.row.startCell" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="form.dataSetType === 'input'" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['system:model:remove']" type="text" icon="el-icon-delete" @click="delFieldHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="form.dataSetType === 'input'" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFieldHandle">{{ $t("添加") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="system:model" />
    </div>
  </div>
</template>

<script>
import { saveModelDataSet, getModelDataSet, delModelDataSetField, getColumnBySql } from '@/api/system/model/data/modelDataSet'
import 'codemirror/theme/ambiance.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint.css'

const CodeMirror = require('codemirror/lib/codemirror')
require('codemirror/addon/edit/matchbrackets')
require('codemirror/addon/selection/active-line')
require('codemirror/mode/sql/sql')
require('codemirror/addon/hint/show-hint')
require('codemirror/addon/hint/sql-hint')
export default {
  data() {
    return {
      // 表单参数
      form: {
        dataSetFieldList: []
      },
      // 遮罩层
      loading: false,
      editor: {},
      // 表单校验
      rules: {
        dataSetName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        dataSetType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        sheetName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        expansionMethod: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        paramField: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        paramType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      dataSetFieldListRules: {
        fieldName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        fieldType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        startCell: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      }
    }
  },
  created() {
  },
  mounted() {
    const mime = 'text/x-mariadb'
    // let theme = 'ambiance'//设置主题，不设置的会使用默认主题
    this.editor = CodeMirror.fromTextArea(this.$refs.searchSql, {
      mode: mime, // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets: true,
      // theme: theme,
      // autofocus: true,
      extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
      hintOptions: { // 自定义提示选项
        tables: {
          users: ['name', 'score', 'birthDate'],
          countries: ['name', 'population', 'size']
        }
      }
    })

    this.editor.on('cursorActivity', function() {
      if (this !== null) {
        this.editor.showHint()
      }
    })
  },
  methods: {
    // 初始化数据
    init(data, dataSourceId) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getModelDataSet(data.id).then(response => {
          this.form = response.data
          this.form.dataSourceId = dataSourceId
          this.editor.setValue(this.form.searchSql !== null ? this.form.searchSql : '')
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        this.form.dataSourceId = dataSourceId
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dataSourceId: undefined,
        dataSetName: undefined,
        dataSetType: undefined,
        sheetName: undefined,
        expansionMethod: undefined,
        paramType: undefined,
        paramField: undefined,
        searchSql: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        delFlag: undefined,
        dataSetFieldList: []
      }
      this.editor.setValue('')
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveModelDataSet(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    getColumnBySql: function() {
      this.form.searchSql = this.editor.getValue()
      if (this.form.searchSql === null || this.form.searchSql.trim() === '') {
        this.$message.error('sql脚本不能为空')
      } else {
        getColumnBySql(this.form).then(response => {
          // 保存之前配置的数据
          const fieldTempMap = {}
          if (this.form.dataSetFieldList) {
            for (let j = 0; j < this.form.dataSetFieldList.length; j++) {
              const filed = this.form.dataSetFieldList[j]
              fieldTempMap[filed.fieldName] = filed
            }
          }
          const fieldList = []
          for (let i = 0; i < response.data.length; i++) {
            let field = {}
            if (fieldTempMap[response.data[i]]) {
              field = fieldTempMap[response.data[i]]
            } else {
              field.fieldName = response.data[i]
              field.fieldType = 'string'
            }
            fieldList.push(field)
          }
          this.form.dataSetFieldList = fieldList
        })
      }
    },
    addFieldHandle() {
      const row = {
        id: undefined,
        dataSetId: undefined,
        fieldName: undefined,
        fieldType: 'string',
        startCell: undefined,
        sort: undefined
      }
      if (!(this.form.dataSetFieldList instanceof Array)) {
        this.$set(this.form, 'dataSetFieldList', [])
      }
      this.$nextTick(() => {
        this.form.dataSetFieldList.push(row)
      })
    },
    // 删除字段列表选中的数据
    delFieldHandle(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delModelDataSetField(id)
          }).then(() => {
          this.form.dataSetFieldList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {})
      } else {
        this.form.dataSetFieldList.splice(index, 1)
      }
    }
  }
}
</script>
<style scoped>
.codeSql {
  font-size: 11pt;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>
